import { reactive } from "vue";

type CartItem = { storeId: number; productId: number; attributeId: number; quantity: number; }

const store = {

  state: reactive({
    cart: [] as CartItem[]
  }),

  setCartAction(item: CartItem): void {
    const i = this.state.cart.findIndex(i => i.storeId == item.storeId && i.productId == item.productId && i.attributeId == item.attributeId);
    if (i == -1) {
      this.state.cart.push(item);
    } else {
      this.state.cart[i].quantity += item.quantity;
    }
  },

  deleteCartItemAction({ storeId, productId, attributeId }: { storeId: number; productId: number; attributeId: number }): boolean {
    const i = store.state.cart.findIndex(item => item.storeId == storeId && item.productId == productId && item.attributeId == attributeId);
    if (i == -1) return false;

    this.state.cart.splice(i, 1);
    return true;
  },

  getCartItemAction({ storeId, productId, attributeId }: { storeId: number; productId: number; attributeId: number }): CartItem | null {
    const i = store.state.cart.findIndex(item => item.storeId == storeId && item.productId == productId && item.attributeId == attributeId);
    if (i == -1) return null;

    return this.state.cart[i];
  },

  clearCartAction(): void {
    this.state.cart.length = 0;
  }
};

export default store;

export type {
  CartItem
}
